
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>表单渲染 API &#8212; Django 3.2.11.dev 文档</title>
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <script type="text/javascript" src="../../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../../genindex.html" />
    <link rel="search" title="搜索" href="../../search.html" />
    <link rel="next" title="部件" href="widgets.html" />
    <link rel="prev" title="表单集函数" href="formsets.html" />



 
<script src="../../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 3.2.11.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="formsets.html" title="表单集函数">previous</a>
     |
    <a href="../index.html" title="API 参考" accesskey="U">up</a>
   |
    <a href="widgets.html" title="部件">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="ref-forms-renderers">
            
  <div class="section" id="s-module-django.forms.renderers">
<span id="s-the-form-rendering-api"></span><span id="module-django.forms.renderers"></span><span id="the-form-rendering-api"></span><h1>表单渲染 API<a class="headerlink" href="#module-django.forms.renderers" title="永久链接至标题">¶</a></h1>
<p>Django 的表单部件是使用 Django 的 <a class="reference internal" href="../../topics/templates.html"><span class="doc">模板引擎系统</span></a> 渲染的。</p>
<p>表单渲染过程可以在几个层次上进行定制：</p>
<ul class="simple">
<li>部件可以指定自定义模板名称。</li>
<li>表单和部件可以指定自定义渲染器类。</li>
<li>组件的模板可以被项目覆盖。（可重用的应用程序通常不应该覆盖内置模板，因为它们可能与项目的自定义模板相冲突。）</li>
</ul>
<div class="section" id="s-the-low-level-render-api">
<span id="s-low-level-widget-render-api"></span><span id="the-low-level-render-api"></span><span id="low-level-widget-render-api"></span><h2>低级渲染 API<a class="headerlink" href="#the-low-level-render-api" title="永久链接至标题">¶</a></h2>
<p>表单模板的渲染是由一个可定制的渲染器类控制的。可以通过更新 <a class="reference internal" href="../settings.html#std:setting-FORM_RENDERER"><code class="xref std std-setting docutils literal notranslate"><span class="pre">FORM_RENDERER</span></code></a> 配置来指定自定义渲染器。它的默认值是 <code class="docutils literal notranslate"><span class="pre">'</span></code><a class="reference internal" href="#django.forms.renderers.DjangoTemplates" title="django.forms.renderers.DjangoTemplates"><code class="xref py py-class docutils literal notranslate"><span class="pre">django.forms.renderers.DjangoTemplates</span></code></a><code class="docutils literal notranslate"><span class="pre">'</span></code>。</p>
<p>你也可以通过设置 <a class="reference internal" href="api.html#django.forms.Form.default_renderer" title="django.forms.Form.default_renderer"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Form.default_renderer</span></code></a> 属性或使用 <a class="reference internal" href="widgets.html#django.forms.Widget.render" title="django.forms.Widget.render"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Widget.render()</span></code></a> 的 <code class="docutils literal notranslate"><span class="pre">renderer</span></code> 参数来提供一个自定义的渲染器。</p>
<p>使用 <a class="reference internal" href="#built-in-template-form-renderers"><span class="std std-ref">内置模板表单渲染器</span></a> 或实现你自己的模板表单渲染器。自定义渲染器必须实现一个 <code class="docutils literal notranslate"><span class="pre">render(template_name,</span> <span class="pre">context,</span> <span class="pre">request=None)</span></code> 方法。它应该返回一个已渲染的模板（作为一个字符串）或引发 <a class="reference internal" href="../../topics/templates.html#django.template.TemplateDoesNotExist" title="django.template.TemplateDoesNotExist"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TemplateDoesNotExist</span></code></a>。</p>
</div>
<div class="section" id="s-built-in-template-form-renderers">
<span id="s-id1"></span><span id="built-in-template-form-renderers"></span><span id="id1"></span><h2>内置模板表单渲染器<a class="headerlink" href="#built-in-template-form-renderers" title="永久链接至标题">¶</a></h2>
<div class="section" id="s-djangotemplates">
<span id="djangotemplates"></span><h3><code class="docutils literal notranslate"><span class="pre">DjangoTemplates</span></code><a class="headerlink" href="#djangotemplates" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.renderers.DjangoTemplates">
<em class="property">class </em><code class="descname">DjangoTemplates</code><a class="headerlink" href="#django.forms.renderers.DjangoTemplates" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>这个渲染器使用一个独立的 <a class="reference internal" href="../../topics/templates.html#django.template.backends.django.DjangoTemplates" title="django.template.backends.django.DjangoTemplates"><code class="xref py py-class docutils literal notranslate"><span class="pre">DjangoTemplates</span></code></a> 引擎（与你在 <a class="reference internal" href="../settings.html#std:setting-TEMPLATES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">TEMPLATES</span></code></a> 配置中设置的内容无关）。它首先从 <code class="docutils literal notranslate"><span class="pre">django/forms/templates</span></code> 内置的表单模板目录中加载模板，然后使用 <a class="reference internal" href="../templates/api.html#django.template.loaders.app_directories.Loader" title="django.template.loaders.app_directories.Loader"><code class="xref py py-class docutils literal notranslate"><span class="pre">app_directories</span></code></a> 加载器从已安装的应用的模板目录中加载模板。</p>
<p>如果你想用你的 <a class="reference internal" href="../settings.html#std:setting-TEMPLATES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">TEMPLATES</span></code></a> 配置中的自定义配置来渲染模板，例如上下文处理器，使用 <a class="reference internal" href="#django.forms.renderers.TemplatesSetting" title="django.forms.renderers.TemplatesSetting"><code class="xref py py-class docutils literal notranslate"><span class="pre">TemplatesSetting</span></code></a> 渲染器。</p>
</div>
<div class="section" id="s-jinja2">
<span id="jinja2"></span><h3><code class="docutils literal notranslate"><span class="pre">Jinja2</span></code><a class="headerlink" href="#jinja2" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.renderers.Jinja2">
<em class="property">class </em><code class="descname">Jinja2</code><a class="headerlink" href="#django.forms.renderers.Jinja2" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>这个渲染器和 <a class="reference internal" href="#django.forms.renderers.DjangoTemplates" title="django.forms.renderers.DjangoTemplates"><code class="xref py py-class docutils literal notranslate"><span class="pre">DjangoTemplates</span></code></a> 渲染器一样，只是它使用了 <a class="reference internal" href="../../topics/templates.html#django.template.backends.jinja2.Jinja2" title="django.template.backends.jinja2.Jinja2"><code class="xref py py-class docutils literal notranslate"><span class="pre">Jinja2</span></code></a> 后台。内置部件的模板位于 <code class="docutils literal notranslate"><span class="pre">django/forms/jinja2</span></code>，安装的应用可以在 <code class="docutils literal notranslate"><span class="pre">jinja2</span></code> 目录下提供模板。</p>
<p>要使用这个后端，你项目中的所有部件和它的第三方应用程序必须有 Jinja2 模板。除非你提供自己的 Jinja2 模板给没有模板的部件，否则你不能使用这个渲染器。例如， <a class="reference internal" href="../contrib/admin/index.html#module-django.contrib.admin" title="django.contrib.admin: Django's admin site."><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.contrib.admin</span></code></a> 由于使用了 Django 模板标签，所以没有为其部件提供 Jinja2 模板。</p>
</div>
<div class="section" id="s-templatessetting">
<span id="templatessetting"></span><h3><code class="docutils literal notranslate"><span class="pre">TemplatesSetting</span></code><a class="headerlink" href="#templatessetting" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.renderers.TemplatesSetting">
<em class="property">class </em><code class="descname">TemplatesSetting</code><a class="headerlink" href="#django.forms.renderers.TemplatesSetting" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>这个渲染器可以让你完全控制部件模板的来源。它使用 <a class="reference internal" href="../../topics/templates.html#django.template.loader.get_template" title="django.template.loader.get_template"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_template()</span></code></a> 根据 <a class="reference internal" href="../settings.html#std:setting-TEMPLATES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">TEMPLATES</span></code></a> 配置中设置的内容来查找部件模板。</p>
<p>使用这个渲染器和内置的部件模板有以下两种方式：</p>
<ul>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">'django.forms'</span></code> 在 <a class="reference internal" href="../settings.html#std:setting-INSTALLED_APPS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">INSTALLED_APPS</span></code></a> 和至少一个引擎有 <a class="reference internal" href="../settings.html#std:setting-TEMPLATES-APP_DIRS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">APP_DIRS=True</span></code></a>。</p>
</li>
<li><p class="first">在你的一个模板引擎的 <a class="reference internal" href="../settings.html#std:setting-TEMPLATES-DIRS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DIRS</span></code></a> 中添加内置部件模板目录。要生成该路径：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">django</span>
<span class="n">django</span><span class="o">.</span><span class="n">__path__</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">+</span> <span class="s1">&#39;/forms/templates&#39;</span>  <span class="c1"># or &#39;/forms/jinja2&#39;</span>
</pre></div>
</div>
</li>
</ul>
<p>使用这个渲染器需要你确保你的项目所需的表单模板可以被找到。</p>
</div>
</div>
<div class="section" id="s-context-available-in-widget-templates">
<span id="context-available-in-widget-templates"></span><h2>部件模板中可用的上下文<a class="headerlink" href="#context-available-in-widget-templates" title="永久链接至标题">¶</a></h2>
<p>部件模板从 <a class="reference internal" href="widgets.html#django.forms.Widget.get_context" title="django.forms.Widget.get_context"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Widget.get_context()</span></code></a> 中接收一个上下文。默认情况下，部件在上下文中只接收一个值，<code class="docutils literal notranslate"><span class="pre">widget</span></code>。这是一个字典，其中包含的值如：</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">name</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">value</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">attrs</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">is_hidden</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">template_name</span></code></li>
</ul>
<p>有些部件会给上下文添加更多信息。例如，所有子类 <code class="docutils literal notranslate"><span class="pre">Input</span></code> 定义了 <code class="docutils literal notranslate"><span class="pre">widget['type']</span></code> 和 <a class="reference internal" href="widgets.html#django.forms.MultiWidget" title="django.forms.MultiWidget"><code class="xref py py-class docutils literal notranslate"><span class="pre">MultiWidget</span></code></a> 定义了 <code class="docutils literal notranslate"><span class="pre">widget['subwidgets']</span></code> 用于循环。</p>
</div>
<div class="section" id="s-overriding-built-in-widget-templates">
<span id="s-id2"></span><span id="overriding-built-in-widget-templates"></span><span id="id2"></span><h2>覆盖内置部件模板<a class="headerlink" href="#overriding-built-in-widget-templates" title="永久链接至标题">¶</a></h2>
<p>每个部件都有一个 <code class="docutils literal notranslate"><span class="pre">template_name</span></code> 属性，其值如 <code class="docutils literal notranslate"><span class="pre">input.html</span></code>。内建的部件模板存储在 <code class="docutils literal notranslate"><span class="pre">django/forms/widgets</span></code> 路径中，你可以为 <code class="docutils literal notranslate"><span class="pre">input.html</span></code> 提供一个自定义模板。你可以通过定义 <code class="docutils literal notranslate"><span class="pre">django/forms/widgets/input.html</span></code> 来为 <code class="docutils literal notranslate"><span class="pre">input.html</span></code> 提供一个自定义模板，例如。参见 <a class="reference internal" href="widgets.html#built-in-widgets"><span class="std std-ref">内置部件</span></a> 了解每个部件的模板名称。</p>
<p>要覆盖部件模板，你必须使用 <a class="reference internal" href="#django.forms.renderers.TemplatesSetting" title="django.forms.renderers.TemplatesSetting"><code class="xref py py-class docutils literal notranslate"><span class="pre">TemplatesSetting</span></code></a> 渲染器。然后覆盖部件模板的工作原理 <a class="reference internal" href="../../howto/overriding-templates.html"><span class="doc">和覆盖项目中的任何其他模板一样</span></a>。</p>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">表单渲染 API</a><ul>
<li><a class="reference internal" href="#the-low-level-render-api">低级渲染 API</a></li>
<li><a class="reference internal" href="#built-in-template-form-renderers">内置模板表单渲染器</a><ul>
<li><a class="reference internal" href="#djangotemplates"><code class="docutils literal notranslate"><span class="pre">DjangoTemplates</span></code></a></li>
<li><a class="reference internal" href="#jinja2"><code class="docutils literal notranslate"><span class="pre">Jinja2</span></code></a></li>
<li><a class="reference internal" href="#templatessetting"><code class="docutils literal notranslate"><span class="pre">TemplatesSetting</span></code></a></li>
</ul>
</li>
<li><a class="reference internal" href="#context-available-in-widget-templates">部件模板中可用的上下文</a></li>
<li><a class="reference internal" href="#overriding-built-in-widget-templates">覆盖内置部件模板</a></li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="formsets.html"
                        title="上一章">表单集函数</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="widgets.html"
                        title="下一章">部件</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../../_sources/ref/forms/renderers.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">12月 07, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="formsets.html" title="表单集函数">previous</a>
     |
    <a href="../index.html" title="API 参考" accesskey="U">up</a>
   |
    <a href="widgets.html" title="部件">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>